# ================= 导入组件 ================
from rest_framework.viewsets import ModelViewSet
from rest_framework.response import Response
from rest_framework.views import APIView
# ================= 序列化的类 ================
from taskweb.serializer import TaskOrderSerializer
# =========== 导入数据类 ============
from taskweb.models import TaskOrder, TaskStatus
# ========= 导入分页的类 ================
from utils.paginations import MyPageNumberPagination
# ========= 导入Filter的类 ==================
from taskweb.filters import TaskOrderFilter
from datetime import datetime
import os
from rest_framework import status
# ========== action 装饰器 =================
from rest_framework.decorators import action


# # 任务订单
class TaskOrderViews(ModelViewSet):
    queryset = TaskOrder.objects.all().order_by('-task_id')
    serializer_class = TaskOrderSerializer

    pagination_class = MyPageNumberPagination

    search_fields = ('task_id', 'name', 'task_desc')
    filter_class = TaskOrderFilter


    @action(methods=['get'], detail=False, url_path="new/taskid")
    def get_new_task_id(self, request, *args, **kwarg):
        # 获取当前的年份
        year = datetime.now().year
        # 获取当前数据库中的所有taskid
        objs = list(TaskOrder.objects.filter(task_id__startswith=str(year)).distinct().values("task_id"))
        # 定义最大的
        if len(objs) == 0:
            return Response({'data': "%d-%03d" %(year, 1)},status=status.HTTP_200_OK)
        # 最大的数字
        max_number = 1
        # 遍历数据
        for item in objs:
            # 切分
            task_id_list = item.get('task_id').split("-")
            # 判断是不是今年的
            if task_id_list[0] == str(year):
                # 判断 是不是大于max_number
                if int(task_id_list[1])>= max_number:
                    max_number = int(task_id_list[1])

        # 返回
        return Response({'data': "%d-%03d" % (year, max_number + 1)}, status=status.HTTP_200_OK)

    def list(self, request, *args, **kwargs):
        # 获取当前的责任人
        q_staff = request.query_params.get('staff', '')
        staff_objs = self.queryset.filter(areaplace__staff__id__icontains=q_staff).distinct()
        # 过滤后把值赋值为queryset --- 引用过滤和search
        queryset = self.filter_queryset(staff_objs)
        # 对数据进行分页
        page = self.paginate_queryset(queryset)
        # 判断是否分页，如果没分页直接返回数据
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)

    def create(self, request, *args, **kwargs):
        # 添加
        # 获取传递的数据
        data = request.data
        try:
            # 获取所有的场地信息
            place_objs = data.get('placecode')
            # 遍历
            for item in place_objs:
                # 判断是否包含场地
                if len(item)<3: continue
                # 开始添加
                TaskOrder.objects.create(task_id=data.get('task_id'),name=data.get('name'), tasktype_id=data.get('tasktype'),
                                         task_desc=data.get('task_desc'),
                                         create_time=datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                                         last_time = data.get('last_time'),
                                         is_cancel=0, is_suspend=0, is_transfer=0,
                                         areaplace_id=item[-1], taskstatus_id=1
                                          )

            return Response({'msg': '返回成功！'}, status=status.HTTP_201_CREATED)
        except Exception as e:
            return Response({'error': '添加出现异常！'}, status=status.HTTP_400_BAD_REQUEST)

    def update(self, request, *args, **kwargs):
        # 获取当前的员工的id
        pk = kwargs.get('pk')
        # 获取表单的数据
        data = request.data
        try:
            # 获取当前的记录
            TaskOrder.objects.filter(pk=pk).update(name=data.get('name'), taskstatus_id=data.get('status'),
                                                   tasktype_id = data.get('tasktype'),
                                                   task_desc=data.get('task_desc'), last_time = data.get('last_time'))

            return Response({'msg': '返回成功！'}, status=status.HTTP_201_CREATED)
        except Exception as e:
            return Response({'error': '修改出现异常！'}, status=status.HTTP_400_BAD_REQUEST)

    @action(methods=['post'], detail=True, url_path="cancel")
    def cancel_task(self, request, *args, **kwargs):
        # 获取操作的Id
        pk = kwargs.get('pk')
        # 修改状态
        TaskOrder.objects.filter(pk=pk).update(is_cancel=1, taskstatus_id=5)
        # 返回
        return Response(status=status.HTTP_200_OK)

    @action(methods=['post'], detail=True, url_path="pause")
    def pause_task(self, request, *args, **kwargs):
        # 获取操作的Id
        pk = kwargs.get('pk')
        # 修改状态
        TaskOrder.objects.filter(pk=pk).update(is_suspend=1,taskstatus_id=4)
        # 返回
        return Response(status=status.HTTP_200_OK)

    @action(methods=['post'], detail=False, url_path="transfer")
    def transfer_task(self, request, *args, **kwargs):
        # 获取当前的工单编号
        order_id = request.data.get('order_id')
        # 获取当前操作的之前的责任人
        last_staff = request.data.get('last_staff')
        # 获取当前选择的责任人
        staff = request.data.get('staff')
        # 获取当前时间
        current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        # 获取当前的记录
        obj_current_order = TaskOrder.objects.filter(id=order_id).update(is_transfer=1, transfer_time=current_time,
                                                                         staff_id = staff, before_staff=last_staff)

        # 返回
        return Response(status=status.HTTP_200_OK)


    @action(methods=['post'], detail=False, url_path="commit")
    def commit_task(self, request, *args, **kwargs):
        # 获取当前的工单编号
        order_id = request.data.get('order_id')
        # 接收描述
        commit_desc = request.data.get("order_desc")
        # 获取当前的工单对象
        order_obj = TaskOrder.objects.filter(id=order_id).first()
        # 获取当前时间
        current_time = datetime.now()
        # 定义状态
        status_obj = TaskStatus.objects.filter(id=2).first()
        # 判断是否超时
        if current_time > order_obj.last_time:
            status_obj = TaskStatus.objects.filter(id=3).first()
        try:
            # 开始写入数据库 [描述，状态，完成时间 ]
            order_obj.taskstatus = status_obj
            order_obj.cmplt_time = current_time.strftime("%Y-%m-%d %H:%M:%S")
            order_obj.cmplt_desc = "<p>" + commit_desc + "</p>"
            # 保存
            order_obj.save()
            #  返回
            return Response(status=status.HTTP_200_OK)
        except Exception as e:
            return Response({'error': "提交工单到数据库出异常"}, status=status.HTTP_400_BAD_REQUEST)


# ==== 上传文件的views ================
from apps.utils import myupload
class UploadView(APIView):
    authentication_classes = []

    def post(self, request, *args, **kwargs):
        # 接受传递过来的文件
        rev_image = request.FILES.get('wangeditor-uploaded-image')
        path = "images"
        # 调用后台通用模块写入文件
        response = myupload.upload_file(rev_image, path, type=2)
        # 如果写入文件正确，继续把文件信息写入到数据库
        if response.get('status'):
            # 返回
            return Response({
                "errno":0,
                "data": {
                    "url": "http://192.168.182.140:8000/api/v1" + os.sep + 'upload' + os.sep  + "images" +  os.path.sep + response.get('data'),
                    "alt": '上传图片',
                    "href": "http://192.168.182.140:8000/api/v1" + os.sep + 'upload' + os.sep  + "images" +  os.path.sep + response.get('data'),

                }
            }, status=status.HTTP_200_OK)
        else:
             return Response({
                 "errno": 1,
                 "message": "失败信息"
             })


class UploadExcelView(APIView):
    authentication_classes = []

    def get(self, request, *args, **kwarg):
        return Response({'code':1000}, status=status.HTTP_200_OK)


from apps.utils import sqlhelper
class EchartsView(APIView):
    authentication_classes = []

    def get(self, request, *args, **kwarg):
        # 准备sql语句
        sql = "Select date, temp_hight, temp_low from CityWeather where City Like '成都%';"
        keys = ['date', 'hight', 'low']
        # 执行
        response = sqlhelper.get_db_data_dict(sql, keys)
        # 获取数据
        data =  response.get('data')
        # 定义集合
        date_list = []
        hight_list = []
        low_list = []
        # 改日期格式
        for index, value in enumerate(data):
            date_list.append(value['date'].strftime("%Y-%m-%d"))
            hight_list.append(value['hight'])
            low_list.append(value['low'])


        return Response({ 'date': date_list, 'hight': hight_list, 'low': low_list}, status=status.HTTP_200_OK)